package com.tanhua.manager.interceptor;

import com.tanhua.manager.domain.Admin;
import com.tanhua.manager.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Value("{tanhua.secret}")
    private String secret;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //1. 获取请求头Authorization
        String authorization = request.getHeader("Authorization");
        if (authorization == null) {
            response.setStatus(401);
            return false;
        }
        //2. 获取token
        String token = authorization.replace("Bearer ", "");
        //3. 判断token是否有效
        if (!JwtUtils.isValidToken(token, secret)) {
            response.setStatus(401);
            return false;
        }
        //4. 解析token获取admin
        Admin admin = JwtUtils.parseToken(token, secret);
        AdminHolder.setAdmin(admin);
        AdminHolder.setToken(token);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        AdminHolder.removeAdmin();
        AdminHolder.removeToken();
    }
}
